<template>
  <Form :rules="rules" @register="formRegister" :schema="schema" />
</template>
<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useValidator } from '@/hooks/web/useValidator'
//import { defineComponent } from 'vue'
import { EmployeeData } from '@/api/table/types'

const { t } = useI18n()
const { formRegister, formMethods } = useForm()
const { required } = useValidator()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const schema = reactive<FormSchema[]>([
  {
    field: 'firstName',
    label: t('demo.firstName'),
    component: 'Input',
    colProps: {
      span: 12
    }
  },
  {
    field: 'lastName',
    label: t('demo.lastName'),
    component: 'Input'
  },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input'
  },
  {
    field: 'phoneNumber',
    label: '手机号',
    component: 'Input'
  },
  {
    field: 'hireDate',
    label: '入职日期',
    component: 'DatePicker'
  }
])

const rules = reactive({
  firstName: [required()],
  lastName: [required()]
})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<EmployeeData>>,
    default: () => null
  }
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>
